#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'ben'
__mtime__ = '16-4-14'
"""

import sys
import logging
import tornado.web
import tornado.ioloop
import json
from baseapi.jsonlib import MyJsonEncoder
from company import clsCompany

logger = logging.getLogger('info')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/home/log/base_info_tornado.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)


class FuzzyHandler(tornado.web.RequestHandler):
    table_name = 'wy_company_base_info'
    cmp_name_col = 'cmp_name'

    def get(self):
        keyword = self.get_argument('keyword')
        logger.log(logging.DEBUG, keyword)

        try:
            cls_company = clsCompany()
            ret = cls_company.fuzzy_name(keyword=keyword, tb_name=self.table_name, col_name=self.cmp_name_col)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'FuzzyHandler/'+str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class BaseInfoHandler(tornado.web.RequestHandler):

    table_name = 'wy_company_base_info'
    cmp_name_col = 'cmp_name'

    def get(self):
        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name,col_name=self.cmp_name_col,col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'BaseInfoHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class EvolutionHandler(tornado.web.RequestHandler):
    table_name = 'wy_cmp_evolution_log_info'
    cmp_name_col = 'cmp_name'

    def get(self):

        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name,col_name=self.cmp_name_col,col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'EvolutionHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class OwnershipHandler(tornado.web.RequestHandler):
    table_name = 'wy_cmp_ownership_structure_info'
    cmp_name_col = 'cmp_name'

    def get(self):

        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name,col_name=self.cmp_name_col,col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'OwnershipHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class ManagerHandler(tornado.web.RequestHandler):
    table_name = 'wy_cmp_main_manager_info'
    cmp_name_col = 'cmp_name'

    def get(self):

        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name, col_name=self.cmp_name_col, col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'ManagerHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class PenaltyHandler(tornado.web.RequestHandler):
    table_name = 'wy_cmp_penalty_info'
    cmp_name_col = 'cmp_name'

    def get(self):

        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name, col_name=self.cmp_name_col, col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'PenaltyHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class AptitudeHandler(tornado.web.RequestHandler):
    table_name = 'wy_cmp_aptitude_info'
    cmp_name_col = 'cmp_name'

    def get(self):
        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name, col_name=self.cmp_name_col, col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'AptitudeHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


class GuaranteeHandler(tornado.web.RequestHandler):

    table_name = 'wy_cmp_external_guarantee_info'
    cmp_name_col = 'cmp_name'

    def get(self):

        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)

        try:
            cls_company = clsCompany()
            ret = cls_company.get_table_info(tb_name=self.table_name, col_name=self.cmp_name_col, col_value=cmp_name)
            res = json.dumps(ret, cls=MyJsonEncoder)

        except Exception, e:
            res = 'GuaranteeHandler/' + str(e)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return

class AllHandler(tornado.web.RequestHandler):

    table_names = ['wy_cmp_aptitude_info','wy_cmp_branch_info','wy_cmp_evolution_log_info',
                   'wy_cmp_external_guarantee_info','wy_cmp_main_manager_info','wy_cmp_ownership_structure_info',
                   'wy_cmp_penalty_info','wy_company_base_info']
    cmp_name_col = 'cmp_name'

    def get(self):
        result = {}
        result['data'] = {}
        cmp_name = self.get_argument('cmp_name')
        logger.log(logging.DEBUG, cmp_name)


        try:
            for tb_name in self.table_names:
                cls_company = clsCompany()
                ret = cls_company.get_table_info(tb_name=tb_name, col_name=self.cmp_name_col,
                                                 col_value=cmp_name)

                if ret and isinstance(ret, dict):
                    if ret.has_key('msg'):
                        ret.pop('msg')

                    if ret.has_key('status'):
                        ret.pop('status')
                result['data'][tb_name] = ret.get('data')
            status = 'true'
            message = '获取成功'
        except Exception, e:
            status = 'false'
            res = 'AllHandler/' + str(e)
            message = res

        result['status'] = status
        result['message'] = message
        res = json.dumps(result, cls=MyJsonEncoder)

        self.set_header("Content-Type", "application/json;charset=utf-8")
        self.write(res)
        logger.log(logging.DEBUG, res)

        return


application = tornado.web.Application([
    (r"/like", FuzzyHandler),
    (r"/exact", BaseInfoHandler),
    (r"/fuzzy",FuzzyHandler),
    (r"/baseinfo",BaseInfoHandler),
    (r"/evolution",EvolutionHandler),
    (r"/ownership",OwnershipHandler),
    (r"/manager", ManagerHandler),
    (r"/penalty", PenaltyHandler),
    (r"/aptitude", AptitudeHandler),
    (r"/guarantee", GuaranteeHandler),
    (r"/all", AllHandler),
])

if __name__ == "__main__":
    # port = 8001
    port = int(sys.argv[1])
    application.listen(port=port)
    tornado.ioloop.IOLoop.instance().start()